import java.io.*;
import java.net.*;
import java.nio.channels.*;
import java.util.Scanner;

public class Updater {
    static String currentVersion;
    static Scanner scanner = new Scanner(System.in);
    static File data = new File("Data");
    static File version = new File("data/version.txt");

    public static void main(String[] args) throws IOException {
        if (!data.exists()) {
            System.out.println("Creating 'Data' directory...");
            data.mkdir();
        }
        else
            System.out.println("'Data' directory found.");

        if (version.exists())
            currentVersion = readFile("data/version.txt").substring(10,12);
        else
            currentVersion = "1.0";

        getNewFiles(VERSION);

        System.out.println("Checking your game version.");

        if (!readFile("data/version.txt").substring(10,12).equals(currentVersion)) {
            currentVersion = readFile("data/version.txt").substring(10,12);
            getNewFiles(BINARY);
            getNewFiles(CHANGELOG);
            System.out.println(readFile("data/changelog.txt"));
        }
        else
            System.out.println("You're using newest version of game.");

        scanner.nextLine();
    }

    static void getNewFiles (String url) throws IOException {
        URL website = new URL(url);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        FileOutputStream fos = new FileOutputStream("data/" + website.getFile().substring(1));
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        if (!website.getFile().substring(1).equals("version.txt"))
            System.out.println("Downloading " + website.getFile().substring(1));
    }

    static String readFile(String filename)
    {
        String content = null;
        File file = new File(filename); //for ex foo.txt
        try {
            FileReader reader = new FileReader(file);
            char[] chars = new char[(int) file.length()];
            reader.read(chars);
            content = new String(chars);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    private static final String VERSION = "http://www.textfighter.zz.mu/version.txt";
    private static final String CHANGELOG =  "http://www.textfighter.zz.mu/changelog.txt";
    private static final String BINARY = "http://www.textfighter.zz.mu/Game.exe";
}
